﻿// DictionarySurrogate.cs
//
// Copyright 2008 by Burt Harris
// Licensed under the Microsoft Public License (Ms-PL)
// See: http://www.codeplex.com/yaml/license
//
namespace YaTools.Yaml.Serialization
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using System.Security.Permissions;

    [DebuggerDisplay("DictionarySurrogate")]
    [Obsolete("Replace with Emitter/Mode/Waypoint")]
    public sealed class DictionarySurrogate : YamlSurrogate 
    {
        // private singleton constructor
        private DictionarySurrogate() { }

        static Uri s_baseUri = new Uri("tag:yatools.net,2009:dictionary,");

        protected override Uri BaseUri
        {
            get { return s_baseUri; }
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
        {
            var writer = context.YamlWriter();

            var dictionary = obj as IDictionary;
            if (dictionary == null)
                throw new ArgumentNullException("obj");

            if (writer.BeginMap(obj, GetUri(obj.GetType()), false))
            {
                try
                {
                    IDictionaryEnumerator de = dictionary.GetEnumerator();
                    while (de.MoveNext())
                    {
                        writer.WriteKey(de.Key, Globals.TypeOfObject);
                        writer.WriteItem(de.Value, Globals.TypeOfObject);
                    }
                }
                finally
                {
                    writer.EndMap();
                }
            }
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            throw new NotImplementedException();
        }

        public static DictionarySurrogate Instance { get { return _instance; } }

        private static DictionarySurrogate _instance = new DictionarySurrogate();
    }
}
